import { watch } from "vue";
import { remainingTime, tipsText } from "./countdown";
import { settings, changeClockPasition } from "./setting";
import { isDevelopment } from "@/utils/env";
import { clockThemeList } from "./constant";

/**
 * 窗口
 */
let newWindow = undefined;

/**
 * 默认窗口尺寸
 */
let defaultWidth = 280;
let defaultHeight = 120;

// 存储watch停止函数的数组
let watchStopHandles = [];

/**
 * 初始化窗口位置
 */
const initWindowPosition = () => {
  if (!newWindow) {
    return;
  }

  // 获取屏幕尺寸
  const { defaultWidth: screenWidth, defaultHeight: screenHeight } = utools.getPrimaryDisplay().workAreaSize;

  // 获取窗口尺寸
  const [windowWidth, windowHeight] = newWindow.getSize();
  // 检查时钟位置设置
  if (Number(settings.value.clockPasitionX) >= 0 && Number(settings.value.clockPasitionY) >= 0) {
    // 时钟位置大于等于0，则定位到指定位置
    newWindow.setBounds({
      x: settings.value.clockPasitionX,
      y: settings.value.clockPasitionY,
      width: windowWidth,
      height: windowHeight,
    });
  } else {
    // 如果时钟位置小于0，则定位到屏幕正中央
    const centerX = Math.round((screenWidth - windowWidth) / 2);
    const centerY = Math.round((screenHeight - windowHeight) / 2);

    newWindow.setBounds({
      x: centerX,
      y: centerY,
      width: windowWidth,
      height: windowHeight,
    });

    // 保存窗口位置
    changeClockPasition(centerX, centerY);
  }
};

/**
 * 动态调整窗口尺寸
 */
export const resizeClockWindow = () => {
  if (!newWindow) {
    return;
  }

  // 获取当前窗口位置
  const [currentX, currentY] = newWindow.getPosition();

  // 计算窗口的新尺寸
  const newWidth = Math.round(defaultWidth * settings.value.clockSizeScale);
  const newHeight = Math.round(defaultHeight * settings.value.clockSizeScale);

  // 设置新的窗口尺寸，保持左上角位置不变
  newWindow.setBounds({
    x: currentX,
    y: currentY,
    width: newWidth,
    height: newHeight,
  });

  // 保存窗口位置
  changeClockPasition(currentX, currentY);
};

/**
 * 窗口位置改变监听
 */
const newWindowPoistionChangeListener = () => {
  window.services.ipcRenderer.on("update-position", (event, { x, y }) => {
    if (!newWindow) return;
    newWindow.setPosition(x, y);
    // 保存窗口位置
    changeClockPasition(x, y);
  });
};

/**
 * 监听倒计时时间变化
 */
const mainWindowRemainingTimeChangeListener = () => {
  const watcher = watch(remainingTime, () => {
    if (!newWindow) return;
    newWindow.webContents.send("update-remainingTime", remainingTime.value);
  });
  watchStopHandles.push(watcher);
};

/**
 * 监听提示文字变化
 */
const mainWindowTipsTextChangeListener = () => {
  const watcher = watch(tipsText, () => {
    if (!newWindow) return;
    newWindow.webContents.send("update-tips-text", tipsText.value);
  });
  watchStopHandles.push(watcher);
};

/**
 * 监听 clockSizeScale 的变化
 */
const mainWindowClockSizeScaleChangeListener = () => {
  const watcher = watch(
    () => settings.value.clockSizeScale,
    () => {
      if (!newWindow) return;
      resizeClockWindow();
      newWindow.webContents.send("update-setting", { ...settings.value });
    }
  );
  watchStopHandles.push(watcher);
};

/**
 * 子窗口启动完成反馈
 */
const newWindowStartedLinstener = () => {
  window.services.ipcRenderer.on("child-started", () => {
    if (!newWindow) return;
    //首次同步倒计时时间
    newWindow.webContents.send("update-remainingTime", remainingTime.value);
    //首次同步提示文字
    newWindow.webContents.send("update-tips-text", tipsText.value);
    //首次同步配置
    newWindow.webContents.send("update-setting", { ...settings.value });
    //首次同步时钟主题
    newWindow.webContents.send(
      "update-clock-theme",
      clockThemeList.find((item) => item.name === settings.value.clockTheme)
    );
  });
};

/**
 * 监听时钟主题的变化
 */
const mainWindowClockThemeChangeListener = () => {
  const watcher = watch(
    () => settings.value.clockTheme,
    () => {
      if (!newWindow) return;
      const clockTheme = clockThemeList.find((item) => item.name === settings.value.clockTheme);
      newWindow.webContents.send("update-clock-theme", clockTheme);
    }
  );
  watchStopHandles.push(watcher);
};

/**
 * 打开时钟
 */
export const openClock = () => {
  // 如果已经打开，则返回
  if (newWindow) {
    return;
  }

  const width = Math.round(defaultWidth * settings.value.clockSizeScale);
  const height = Math.round(defaultHeight * settings.value.clockSizeScale);

  // 调用 uTools API 创建新窗口
  newWindow = utools.createBrowserWindow(
    "index.html", // 新窗口页面路径
    {
      width,
      height,
      // title: "新窗口",
      frame: false, // 无边框
      transparent: true, // 背景透明
      alwaysOnTop: true, // 始终置顶
      skipTaskbar: true, // 不在任务栏显示
      resizable: false, //禁止用户拖动窗口边缘来放大 / 缩小
      backgroundColor: "#00000000", //补充设置窗口背景为全透明
      webPreferences: {
        // 预加载脚本
        preload: "child-preload/preload.js",
      },
    },
    () => {
      // 显示窗口
      newWindow.show();

      // 开发模式才自动打开调试工具
      if (isDevelopment()) {
        newWindow.webContents.openDevTools({
          mode: "detach", // 独立窗口模式
        });
      }

      // 设置窗口位置
      initWindowPosition();
    }
  );

  //子窗口移动窗口请求
  newWindowPoistionChangeListener();

  //监听倒计时时间变化
  mainWindowRemainingTimeChangeListener();

  //监听提示文字变化
  mainWindowTipsTextChangeListener();

  // 只监听 clockSizeScale 的变化
  mainWindowClockSizeScaleChangeListener();

  // 监听时钟主题的变化
  mainWindowClockThemeChangeListener();

  //子窗口启动完成反馈
  newWindowStartedLinstener();
};

/**
 * 关闭时钟
 */
export const closeClock = () => {
  //关闭窗口
  if (newWindow) {
    newWindow.close();
    newWindow = null;
  }

  // 停止所有watch监听
  watchStopHandles.forEach((stop) => stop());
  watchStopHandles = [];
};
